package com.yao.sys.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yao.common.bean.PageQueryBean;
import com.yao.common.helper.ValidateHelper;
import com.yao.common.resp.ApiResponse;
import com.yao.sys.entity.dto.UserDto;
import com.yao.sys.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户表 Controller
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2020-04-09
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping(value = "/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "新增用户", notes = "新增用户")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ApiResponse<Object> add(@RequestBody UserDto model) {

        ValidateHelper.validateNull(model, new String[] {"userName", "idCard", "phone"});

        userService.add(model);

        return ApiResponse.success();
    }

    @ApiOperation(value = "修改用户", notes = "修改用户")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ApiResponse<Object> update(@RequestBody UserDto model) {

        ValidateHelper.validateNull(model, new String[] {"id", "userName", "idCard", "phone"});

        userService.modifyById(model);

        return ApiResponse.success();
    }

    @ApiOperation(value = "删除用户", notes = "逻辑删除用户")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public ApiResponse<Object> deleteById(@PathVariable("id") Integer id) {

        ValidateHelper.validateId(id);

        userService.removeById(id);

        return ApiResponse.success();
    }

    @ApiOperation(value = "获取用户", notes = "获取用户")
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public ApiResponse<UserDto> get(@PathVariable("id") Integer id) {

        ValidateHelper.validateId(id);

        return ApiResponse.success(userService.byId(id));
    }

    @ApiOperation(value = "用户列表(分页)", notes = "用户列表")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ApiResponse<IPage<UserDto>> list(@RequestBody PageQueryBean<UserDto> queryBean) {

        Page<UserDto> page = userService.page(new Page<>(queryBean.getCurrent(), queryBean.getSize()));

        page.getRecords().stream().forEach(e -> e.fill(e));

        return ApiResponse.success(page);
    }

}